package com.zhouqinuan.spring.cloud.develop.framework.base.config.distributed.id;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.zhouqinuan.spring.cloud.develop.framework.base.util.IpUtil;

@Configuration
public class SnowFlakeIdGeneratorConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean
    @ConditionalOnMissingBean(SnowFlakeIdGenerator.class)
    public SnowFlakeIdGenerator snowFlakeIdGenerator() {
        String fullName = applicationName + IpUtil.getLocalIP();

        long workerId = Math.abs(Objects.hashCode(fullName) % 32);
        long datacenterId = Math.abs(Objects.hashCode(fullName) % 32);

        return new SnowFlakeIdGenerator(workerId, datacenterId);
    }
}
